<template>
  <view class="puzzle-container">
    <!-- 顶部信息 -->
    <view class="game-header">
      <view class="score-box">
        <text class="score-label">当前积分</text>
        <text class="score-value">{{ score }}</text>
      </view>
      <button class="reset-btn" @tap="resetGame">
        <text class="bi bi-arrow-clockwise"></text> 重新开始
      </button>
    </view>

    <!-- 鼓励文字 -->
    <view class="encourage-text animate__animated" :class="encourageClass">
      {{ encourageText }}
    </view>

    <!-- 拼图游戏区域 -->
    <view class="puzzle-board">
      <view 
        v-for="(piece, index) in puzzlePieces" 
        :key="index"
        class="puzzle-piece"
        :class="{ 
          'correct-position': piece.isCorrect,
          'animate__animated': true,
          'animate__pulse': piece.isSelected,
          'animate__bounceIn': piece.isCorrect && !completedBefore
        }"
        :style="{ 
          backgroundImage: `url(${currentImage})`,
          backgroundPosition: `${piece.bgPosX}% ${piece.bgPosY}%`,
          backgroundSize: '300%',
          order: piece.currentPos
        }"
        @tap="selectPiece(index)"
      ></view>
    </view>

    <!-- 预览图 -->
    <view class="preview-wrapper">
      <image 
        :src="url('s',currentImage,'png')" 
        class="preview-image" 
        mode="aspectFit"
      />
    </view>

    <!-- 图片选择区域 -->
    <view class="image-selector">
      <view 
        v-for="(image, index) in imageOptions" 
        :key="index"
        class="image-option"
        :class="{ 'selected': currentImageIndex === index }"
        @tap="changeImage(index)"
      >
        <image :src="url('s',image,'png')" mode="aspectFill" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const score = computed(() => store.score);
const url = $url
// 游戏图片选项 (使用傩面具图片)
const imageOptions = ref([
  '1',
  '2',
  '3',
  '4',
]);

// 游戏数据
const puzzlePieces = ref([]);
const currentImageIndex = ref(0);
const currentImage = computed(() => imageOptions.value[currentImageIndex.value]);
const selectedPieceIndex = ref(null);
const completedPuzzles = ref({});
const completedBefore = ref(false);
const encourageText = ref('开始拼装傩面具拼图吧！');
const encourageClass = ref('');

// 鼓励文字库
const encourageTexts = {
  start: ['开始拼装傩面具拼图吧！', '让我们一起探索傩文化！'],
  progress: ['很好，继续加油！', '拼图正确！', '你很有天赋！'],
  complete: ['太棒了！拼图完成！', '你是拼图大师！', '你太懂傩文化了！']
};

// 初始化拼图
const initPuzzle = () => {
  const pieces = [];
  completedBefore.value = !!completedPuzzles.value[currentImageIndex.value];
  
  // 创建3x3=9块拼图
  for (let i = 0; i < 9; i++) {
    const row = Math.floor(i / 3);
    const col = i % 3;
    
    pieces.push({
      id: i,
      correctPos: i,
      currentPos: i,
      bgPosX: col * 50,  // 背景位置 X (0%, 50%, 100%)
      bgPosY: row * 50,  // 背景位置 Y (0%, 50%, 100%)
      isCorrect: false,
      isSelected: false
    });
  }
  
  // 随机打乱拼图顺序
  shufflePieces(pieces);
  puzzlePieces.value = pieces;
  
  // 显示鼓励文字
  showEncourageText('start');
};

// 打乱拼图顺序
const shufflePieces = (pieces) => {
  let positions = pieces.map((_, i) => i);
  
  // Fisher-Yates 洗牌算法
  for (let i = positions.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [positions[i], positions[j]] = [positions[j], positions[i]];
  }
  
  // 确保不会生成已解决的拼图
  if (positions.every((pos, i) => pos === i)) {
    shufflePieces(pieces);
    return;
  }
  
  // 更新拼图位置
  pieces.forEach((piece, index) => {
    piece.currentPos = positions[index];
    piece.isCorrect = piece.currentPos === piece.correctPos;
  });
};

// 选择拼图
const selectPiece = (index) => {
  const piece = puzzlePieces.value[index];
  
  // 如果已经正确，就不能选择
  if (piece.isCorrect) return;
  
  if (selectedPieceIndex.value === null) {
    // 第一次选择
    selectedPieceIndex.value = index;
    piece.isSelected = true;
  } else {
    // 第二次选择，交换两块拼图
    const firstPiece = puzzlePieces.value[selectedPieceIndex.value];
    const secondPiece = piece;
    
    // 交换位置
    const tempPos = firstPiece.currentPos;
    firstPiece.currentPos = secondPiece.currentPos;
    secondPiece.currentPos = tempPos;
    
    // 检查是否放到正确位置
    firstPiece.isCorrect = firstPiece.currentPos === firstPiece.correctPos;
    secondPiece.isCorrect = secondPiece.currentPos === secondPiece.correctPos;
    
    // 取消选择状态
    firstPiece.isSelected = false;
    selectedPieceIndex.value = null;
    
    // 检查是否完成拼图
    checkCompletion();
  }
};

// 检查是否完成拼图
const checkCompletion = () => {
  const isComplete = puzzlePieces.value.every(piece => piece.isCorrect);
  
  if (isComplete) {
    // 标记为已完成
    completedPuzzles.value[currentImageIndex.value] = true;
    
    // 显示祝贺文字
    showEncourageText('complete');
    
    // 增加积分奖励
    const additionalScore = completedBefore.value ? 5 : 10;
    store.updateScore(store.score + additionalScore);
    
    // 显示祝贺弹窗
    setTimeout(() => {
      uni.showModal({
        title: '恭喜完成拼图！',
        content: `获得${additionalScore}积分奖励！继续挑战其他拼图吧！`,
        showCancel: false
      });
    }, 500);
  } else {
    // 检查正确的拼图数量
    const correctCount = puzzlePieces.value.filter(p => p.isCorrect).length;
    
    if (correctCount > 0) {
      showEncourageText('progress');
    }
  }
};

// 切换图片
const changeImage = (index) => {
  if (currentImageIndex.value === index) return;
  
  // 询问是否切换图片
  uni.showModal({
    title: '提示',
    content: '切换图片将重置当前拼图进度，确定要继续吗？',
    success: (res) => {
      if (res.confirm) {
        currentImageIndex.value = index;
        resetGame();
      }
    }
  });
};

// 显示鼓励文字
const showEncourageText = (type) => {
  const texts = encourageTexts[type];
  encourageText.value = texts[Math.floor(Math.random() * texts.length)];
  encourageClass.value = 'animate__bounceIn';
  
  setTimeout(() => {
    encourageClass.value = '';
  }, 1000);
};

// 重置游戏
const resetGame = () => {
  selectedPieceIndex.value = null;
  initPuzzle();
};

// 页面加载时初始化
onMounted(() => {
  completedPuzzles.value = {};
  initPuzzle();
});
</script>

<style lang="scss" scoped>
.puzzle-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 40rpx;
}

.score-box {
  background: #fff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  
  .score-label {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
  }
  
  .score-value {
    font-size: 32rpx;
    font-weight: bold;
    color: var(--td-brand-color);
  }
}

.reset-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
  background: var(--td-brand-color);
  color: #fff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  
  &:active {
    opacity: 0.9;
  }
}

.encourage-text {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: var(--td-brand-color);
  margin: 30rpx 0;
  min-height: 50rpx;
}

.puzzle-board {
  width: 100%;
  aspect-ratio: 1;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 10rpx;
  margin-bottom: 30rpx;
}

.puzzle-piece {
  aspect-ratio: 1;
  background-color: #f0f0f0;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &.correct-position {
    box-shadow: 0 0 10rpx rgba(0, 128, 0, 0.5);
    border: 2rpx solid green;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.preview-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 30rpx 0;
}

.preview-image {
  width: 60%;
  height: 300rpx;
  opacity: 0.4;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  border: 2rpx dashed var(--td-brand-color);
}

.image-selector {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-top: 30rpx;
}

.image-option {
  width: 22%;
  aspect-ratio: 1;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.2);
  transition: all 0.3s ease;
  
  &.selected {
    transform: scale(1.1);
    box-shadow: 0 0 0 4rpx var(--td-brand-color);
  }
  
  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

// 确保动画库已引入
@import 'animate.css';
</style> 